import { createVNode, Ref, toRaw } from "vue";
import { AxiosResponse } from "axios";
import { message, Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { IModelPageTableState } from "../_types/table/page-table-state";
import { IModelFormState, ModelFormOtherConfig, ModelFormStatus } from "../_types/form/model-form";
import { redirectTo } from "./common-kit";
import { ModelApi } from "/@/_types/api";

import { t } from '/@/i18n/index'



export function useModelForm(antFormRef: Ref<any>, modelValueRef: Ref<any>, primaryValue: string, modelApi: ModelApi, otherConfig?: ModelFormOtherConfig): IModelFormState {
    const modelFormState: IModelFormState = {
        modelFormStatus: primaryValue ? ModelFormStatus.Edit : ModelFormStatus.Add,
        //新增方法
        add: async () => {
            return antFormRef.value
                .validate()
                .then(async () => {
                    const res = await modelApi.add(toRaw(modelValueRef.value), otherConfig?.extraData);
                    console.log("model-kit insert", res);
                    //如果为新增 成功后 配置了主键key和编辑页面的url 直接进行跳转
                    if (modelApi.primaryKey && otherConfig?.editPageUrl)
                        redirectTo(otherConfig.editPageUrl + res.data.data[modelApi.primaryKey]);
                    return await Promise.resolve(res);
                }).catch((error: ValidateErrorEntity<any>) => {
                    console.log("model-kit", error)
                    return Promise.reject(error);
                });
        },
        //更新方法
        update: async () => {
            return antFormRef.value
                .validate()
                .then(async () => {
                    const res = await modelApi.update(toRaw(modelValueRef.value), otherConfig?.extraData);
                    console.log("model-kit update", res);
                    return await Promise.resolve(res);
                }).catch((error: ValidateErrorEntity<any>) => {
                    console.log("model-kit", error)
                    return Promise.reject(error);
                });
        },
        //新增或者更新
        save: async () => {
            if (modelFormState.modelFormStatus == ModelFormStatus.Add) {
                return modelFormState.add();
            } else {
                return modelFormState.update();
            }
        }
    }
    //这里我们需要来一个
    if (modelFormState.modelFormStatus == ModelFormStatus.Add) {
        if (otherConfig?.initAdd instanceof Function) {
            //为了让initAdd有更广泛的支持 且initAddAfter本就在他之后 没必要定义initAdd还定义initAddAfter ,initEdit也一样
            otherConfig.initAdd();
        } else {
            modelApi.newModel(otherConfig?.newModelParam).then(res => {
                modelValueRef.value = res.data.data;
                if (otherConfig?.initAddAfter instanceof Function) {
                    otherConfig.initAddAfter();
                }
            })
        }
    } else if (modelFormState.modelFormStatus == ModelFormStatus.Edit) {
        if (otherConfig?.initEdit instanceof Function) {
            otherConfig.initEdit();
        } else {
            modelApi.id(primaryValue, otherConfig?.extraData).then((res) => {
                modelValueRef.value = res.data.data
                if (otherConfig?.initEditAfter instanceof Function) {
                    otherConfig.initEditAfter();
                }
            });
        }

    }
    return modelFormState;
}


/**
 * 得到常用的方法
 * @param modelPageTableRef page-table ref
 * @param modelApi model api对象
 * @param queryParam page-table 查询参数
 * @returns 
 */
export function useModelPageTable(modelPageTableRef: Ref<any>, modelApi: ModelApi, queryParam?: any) {
    const modelPageTableState: IModelPageTableState = {
        primaryKey: modelApi.primaryKey,
        loadData: (param: any) => {
            return modelApi.page({ ...param, ...queryParam });
        },
        getTableHelper: () => {
            return modelPageTableRef.value.helper;
        },
        //搜索表格
        searchTable: () => {
            modelPageTableState.getTableHelper().serachTable();
        },
        //重载表格
        reloadTable: () => {
            modelPageTableState.getTableHelper().reloadTable();
        },
        getSelectRows: () => {
            if (!modelPageTableRef.value) {
                return [];
            }
            return modelPageTableState.getTableHelper().getSelectData().selectedRows;
        },
        deleteSelectData: () => {
            const dataList = modelPageTableState.getSelectRows();
            //做一个删除出前拦截
            if (!dataList || dataList.length == 0) {
                message.warning(t('kit.model.noSelectDeleteData'));
                return;
            } else {
                //您确定要删除选择的数据么
                Modal.confirm({
                    title: t('kit.model.deleteData'),
                    icon: createVNode(ExclamationCircleOutlined),
                    content: t('kit.model.sureDeleteData'),
                    okType: 'primary',
                    onOk() {
                        modelApi.deleteBatch(dataList).then(() => {
                            modelPageTableState.reloadTable();
                        })
                    }
                });
            }

        },
        downloadExcel: (param: any) => {
            return modelApi.downloadExcel({ ...param, ...queryParam });
        }
    }
    return modelPageTableState;
}

